package com.voice.client.channel.handle.impl;

import com.voice.client.connection.DeviceStreamConnection;
import com.voice.core.message.DeviceBytesMessage;
import com.voice.client.message.impl.MessageClientImpl;
import com.voice.core.entity.HttpHeader;
import com.voice.core.connection.Connection;
import com.voice.core.connection.ConnectionStatus;
import com.voice.core.connection.impl.SocketChannelConnectionImpl;
import com.voice.core.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class DeviceChannelStreamListener extends AbstractStreamListenerHandler<DeviceStreamConnection> {

    private MessageClientImpl messageClient;

    public DeviceChannelStreamListener(MessageClientImpl messageClient) {
        this.messageClient = messageClient;
    }

    @Override
    public DeviceStreamConnection conversionTo(HttpHeader requestHeader, Connection connection) {
        String deviceKey = requestHeader.get("deviceKey", String.class);
        String userId=requestHeader.get("userId",String.class);
        DeviceStreamConnection deviceConnection=new DeviceStreamConnection((SocketChannelConnectionImpl) connection,userId, deviceKey);
        return deviceConnection;
    }

    @Override
    public void onStreamRead(DeviceStreamConnection connection, byte[] bytes) {
        DeviceBytesMessage deviceBytesMessage=new DeviceBytesMessage(connection.getUserId(),connection.getDeviceKey(),bytes);
        this.messageClient.onDataRead(connection, null, ResponseUtil.success("/message/byte",deviceBytesMessage));
    }

    @Override
    public void onStatusChange(ConnectionStatus status, DeviceStreamConnection connection) {
        switch (status) {
            case CLOSED:
                log.info("DeviceStreamConnection:{} 断开",connection);
                break;
            case AUTHORIZED:
                log.info("DeviceStreamConnection:{} 连接",connection);
                break;
        }
    }

}
